﻿using Engine;
using Engine.Graphics;
using Game;

namespace SAGhoul.ParticleSystem
{
	public class ExplosionParticleEffect : ParticleSystem<ExplosionParticleEffect.Particle>
	{
		public class Particle : Game.Particle
		{
			public float Strength;
			public Vector3 InitialPosition;
			public Vector3 Velocity;
			public float Life;
			public float MaxLife;
		}

		public Vector3 m_position;
		public float m_radius;
		public Engine.Random m_random = new();
		public bool m_isDone;

		public ExplosionParticleEffect(Vector3 position, float radius)
			: base(200)
		{
			m_position = position;
			m_radius = radius;
			Texture = ContentManager.Get<Texture2D>("Textures/FireParticle");
			TextureSlotsCount = 3;
			GenerateParticles();
		}

		public void GenerateParticles()
		{
			int particleCount = MathUtils.Min((int)(m_radius * m_radius * 10f), Particles.Length);
			for (int i = 0; i < particleCount; i++)
			{
				Particle particle = Particles[i];
				particle.IsActive = true;
				particle.Position = m_position;
				particle.InitialPosition = m_position;
				particle.Velocity = m_random.Vector3(1f) * m_random.Float(2f, 5f);
				particle.Size = new Vector2(m_random.Float(0.3f, 0.7f));
				particle.Strength = m_random.Float(0.5f, 1f);
				particle.Color = Color.White;
				particle.Life = particle.MaxLife = m_random.Float(0.5f, 1.5f);
			}
		}

		public override bool Simulate(float dt)
		{
			if (m_isDone)
				return true;

			bool hasActiveParticles = false;
			for (int i = 0; i < Particles.Length; i++)
			{
				Particle particle = Particles[i];
				if (!particle.IsActive)
					continue;

				hasActiveParticles = true;
				particle.Life -= dt;
				if (particle.Life <= 0f)
				{
					particle.IsActive = false;
					continue;
				}

				particle.Position += particle.Velocity * dt;
				float progress = 1f - (particle.Life / particle.MaxLife);
				progress = MathUtils.Saturate(progress);
				particle.TextureSlot = (int)(progress * 8f);
				particle.Color = Color.White * (particle.Life / particle.MaxLife);
			}

			if (!hasActiveParticles)
				m_isDone = true;

			return m_isDone;
		}
	}
}
